package com.jdew.thkj.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.jdew.thkj.R;
import com.jdew.thkj.adapter.RankAdapter;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.bean.RankBean;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.onitemInterface.OnItemClickListener;
import com.jdew.thkj.utils.DeviceUtils;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.utils.WeiboDialogUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class RankActivity extends BaseActivity {
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.recycleView)
    RecyclerView recycleView;
    @Bind(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @Bind(R.id.nonetwork)
    TextView nonetwork;
    private int page = 1;
    private RankAdapter adapter;
    private boolean isLoading = true;
    private String ItemId;
    private int type = 1;
    private String biaoti;
    private List<RankBean.DataBean> list = new ArrayList<>();


    @Override
    public int bindLayout() {
        return R.layout.activity_go;
    }

    @Override
    public void initView(View view) {
        back.setVisibility(View.VISIBLE);
        sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        back.setOnClickListener(this);
        nonetwork.setOnClickListener(this);
        type = getIntent().getIntExtra("type", 1);
        biaoti = getIntent().getStringExtra("title");
        title.setText(biaoti);
        adapter = new RankAdapter(this, list);
        setRcycleview(recycleView, adapter);
        initRefresh(type);
        getType(type);
        setRecycleView(type);
        adapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (!RegexValidateUtils.isFastClick()) {
                    return;
                }
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(RankActivity.this, LoginActivity.class));
                } else if (sp.getString("UserSjPhone", "").equals("") && (!sp.getString("SpareTwo", "").equals("1"))) {
                    toset("检测到您还没有绑定上级,请到我的页面绑定上级");
                } else {
                    ItemId = list.get(position).getTb_goods_id() + "";
                    Bundle b = new Bundle();
                    b.putSerializable("itemId", ItemId);
                    startActivity(TbProductDetailActivity.class, b);
                }
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.nonetwork: {
                getType(type);
            }
            break;
            default:
                break;
        }
    }

    public void RequestData() {
        if (!DeviceUtils.isNetworkAvalible(this)) {
            swipeRefreshLayout.setVisibility(View.GONE);
            nonetwork.setVisibility(View.VISIBLE);
            ToastUtils.getInstance(this).showMessage( "网络连接错误请检查");
            return;
        } else {
            swipeRefreshLayout.setVisibility(View.VISIBLE);
            nonetwork.setVisibility(View.GONE);
        }
        if (null != mWeiboDialog) {
            mWeiboDialog.dismiss();
        }
        mWeiboDialog = WeiboDialogUtils.createLoadingDialog(this);
        String timesamp=RegexValidateUtils.getTime13();
        String numsamp=RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetDailyPush(page, RegexValidateUtils.getUniquePsuedoID(),timesamp,numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp+numsamp+RegexValidateUtils.getUniquePsuedoID()+sp.getString("SignToken","")+"PageIndex"+page)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onError(Throwable e) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onNext(JSONObject obj) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
                if (obj.getString("code").equals("0")) {
                    RankBean bean = JSONObject.parseObject(obj.toString(), RankBean.class);
                    if (null == bean.getData()) {
                        return;
                    }
                    if (page == 1) {
                        list.clear();
                    }
                    list.addAll(bean.getData());
                    adapter.setDataList(list);
                    isLoading = false;
                    adapter.changeMoreStatus(adapter.LOADING_MORE);
                    swipeRefreshLayout.setRefreshing(false);
                }
            }
        });
    }

    public void RequestGo() {
        if (!DeviceUtils.isNetworkAvalible(this)) {
            swipeRefreshLayout.setVisibility(View.GONE);
            nonetwork.setVisibility(View.VISIBLE);
            ToastUtils.getInstance(this).showMessage( "网络连接错误请检查");
            return;
        } else {
            swipeRefreshLayout.setVisibility(View.VISIBLE);
            nonetwork.setVisibility(View.GONE);
        }
        if (null != mWeiboDialog) {
            mWeiboDialog.dismiss();
        }
        mWeiboDialog = WeiboDialogUtils.createLoadingDialog(this);
        String timesamp=RegexValidateUtils.getTime13();
        String numsamp=RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetAllDaySales(page, RegexValidateUtils.getUniquePsuedoID(),timesamp,numsamp,MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp+numsamp+RegexValidateUtils.getUniquePsuedoID()+sp.getString("SignToken","")+"PageIndex"+page)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onError(Throwable e) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }


            @Override
            public void onNext(JSONObject obj) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
                if (obj.getString("code").equals("0")) {
                    RankBean bean = JSONObject.parseObject(obj.toString(), RankBean.class);
                    if (null == bean.getData()) {
                        return;
                    }
                    if (page == 1) {
                        list.clear();
                    }
                    list.addAll(bean.getData());
                    adapter.setDataList(list);
                    isLoading = false;
                    adapter.changeMoreStatus(adapter.LOADING_MORE);
                    swipeRefreshLayout.setRefreshing(false);
                }
            }
        });
    }


    private void initRefresh(final int type) {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getType(type);
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    public void setRecycleView(final int type) {
        recycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                LinearLayoutManager linearManager = null;
                if (layoutManager instanceof LinearLayoutManager) {
                    linearManager = (LinearLayoutManager) layoutManager;
                }
                int lastVisibleItemPosition = linearManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    boolean isRefreshing = swipeRefreshLayout.isRefreshing();
                    if (isRefreshing) {
                        adapter.notifyItemRemoved(adapter.getItemCount());
                        return;
                    }
                    if (!isLoading) {
                        isLoading = true;
                        page++;
                        getType(type);
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    public void getType(int type) {
        if (type == 1) {
            RequestData();
        } else if (type == 2) {
            RequestGo();
        }
    }
}
